<template>
  <div class="message-content11">
    <div ref="textRef" class="leading-relaxed break-words">
      <div
        class="markdown-body"
        v-html="renderedText"
        @click="handleClick"
      ></div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import MarkdownIt from "markdown-it";
import mila from "markdown-it-link-attributes";
import mdKatex from "@traptitech/markdown-it-katex";
import hljs from "highlight.js";
import { formatMarkdownNew } from "@/utils/formatMarkdown";
import { ElMessage } from "element-plus";
import "highlight.js/styles/github.css";

// Props 定义
const props = defineProps({
  textInfo: {
    type: String,
    default: "",
  },
});

// 定义 emit
const emit = defineEmits(["regenerate"]);

// 创建 markdown-it 实例
const mdi = ref(null);

// 使用 ref 跟踪复制状态
const isCopying = ref(false);
const isRegenerating = ref(false);

// 统一的点击处理函数
const handleClick = async (event) => {
  const copyBtn = event.target.closest(".copy-btn");
  const regenerateBtn = event.target.closest(".regenerate-btn");

  if (copyBtn) {
    await handleCopyClick(copyBtn);
  } else if (regenerateBtn) {
    await handleRegenerate(regenerateBtn);
  }
};

// 复制功能
const handleCopyClick = async (btn) => {
  if (isCopying.value) return;

  try {
    isCopying.value = true;
    const code = decodeURIComponent(btn.dataset.code);
    await navigator.clipboard.writeText(code);

    const originalText = btn.textContent;
    btn.textContent = "已复制!";
    btn.classList.add("copied");

    ElMessage.success("代码已复制到剪贴板");

    setTimeout(() => {
      btn.textContent = originalText;
      btn.classList.remove("copied");
      isCopying.value = false;
    }, 2000);
  } catch (err) {
    console.error("复制失败:", err);
    ElMessage.error("复制失败，请重试");
    isCopying.value = false;
  }
};

// 重新生成功能
const handleRegenerate = async (btn) => {
  if (isRegenerating.value) return;

  try {
    isRegenerating.value = true;
    btn.classList.add("regenerating");

    // 触发重新生成事件
    emit("regenerate");

    // 更新按钮状态
    const originalText = btn.textContent;
    btn.textContent = "重新生成中...";

    // 这里可以添加实际的重新生成逻辑

    setTimeout(() => {
      btn.textContent = originalText;
      btn.classList.remove("regenerating");
      isRegenerating.value = false;
    }, 2000);
  } catch (err) {
    console.error("重新生成失败:", err);
    ElMessage.error("重新生成失败，请重试");
    btn.textContent = "重新生成";
    btn.classList.remove("regenerating");
    isRegenerating.value = false;
  }
};

// 代码高亮和添加复制按钮的函数
const highlightCode = (str, lang) => {
  const uniqueId = `code-${Date.now()}-${Math.random()
    .toString(36)
    .substr(2, 9)}`;

  if (!lang) {
    return `<pre class="code-block" id="${uniqueId}"><code>${str}</code><div class="code-block-header"><button type="button" class="copy-btn" data-code="${encodeURIComponent(
      str
    )}">复制代码</button></div></pre>`;
  }

  let code = "";
  try {
    if (hljs.getLanguage(lang)) {
      code = hljs.highlight(str, {
        language: lang,
        ignoreIllegals: true,
      }).value;
    } else {
      code = hljs.highlightAuto(str).value;
    }
  } catch (e) {
    code = str;
  }

  return `<pre class="code-block" id="${uniqueId}"><code class="hljs language-${lang}">${code}</code><div class="code-block-header"><span class="lang-label">${lang}</span><button type="button" class="copy-btn" data-code="${encodeURIComponent(
    str
  )}">复制代码</button></div></pre>`;
};

// 初始化 markdown-it
onMounted(() => {
  mdi.value = new MarkdownIt({
    html: true,
    linkify: true,
    highlight(code, language) {
      const validLang = hljs.getLanguage(language);
      if (validLang) {
        const lang = language || "";
        return hljs.highlight(code, { language: lang }).value;
      }
      return hljs.highlightAuto(code).value;
    },
  });

  // 使用插件
  mdi.value.use(mila, { attrs: { target: "_blank", rel: "noopener" } });
  mdi.value.use(mdKatex, {
    blockClass: "katexmath-block rounded-md p-[10px]",
    errorColor: " #cc0000",
  });

  // 添加点击事件监听器
  document.addEventListener("click", handleClick);
});

// 清理事件监听器
onUnmounted(() => {
  document.removeEventListener("click", handleClick);
});

// 计算属性处理文本
const renderedText = computed(() => {
  if (!mdi.value) return "";

  const value = props.textInfo.replaceAll("*", "") || "";
  return mdi.value.render(value);
});

// 格式化 markdown
</script>

<style lang="scss" scoped>
@import "./style/index.scss";

.markdown-body {
  .code-block {
    position: relative;
    margin: 1em 0;
    padding: 1em;
    background-color: #f6f8fa;
    border-radius: 6px;
    overflow: visible;
    font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;

    &:hover .code-block-header {
      opacity: 1;
    }

    code {
      display: block;
      line-height: 1.5;
      font-size: 14px;
      overflow-x: auto;
      color: #333;
    }

    .code-block-header {
      position: absolute;
      top: 0.5em;
      right: 0.5em;
      display: flex;
      align-items: center;
      gap: 8px;
      opacity: 0;
      transition: opacity 0.2s;

      .lang-label {
        font-size: 12px;
        color: #666;
        padding: 2px 6px;
        background-color: #e1e4e8;
        border-radius: 3px;
      }

      .copy-btn {
        position: relative;
        z-index: 1; // 确保按钮在最上层
        pointer-events: auto; // 确保按钮可点击
        padding: 4px 8px;
        font-size: 12px;
        color: #666;
        background-color: #fff;
        border: 1px solid #d1d5da;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.2s;

        &:hover {
          background-color: #f3f4f6;
          border-color: #b1b5ba;
        }

        &.copied {
          pointer-events: none; // 复制后禁用点击
          color: #28a745;
          border-color: #28a745;
          background-color: #dcffe4;
        }

        &:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }
      }
    }
  }

  // 代码高亮样式
  .hljs {
    background: transparent;
    padding: 0;

    .hljs-keyword {
      color: #d73a49;
    }
    .hljs-string {
      color: #032f62;
    }
    .hljs-number {
      color: #005cc5;
    }
    .hljs-function {
      color: #6f42c1;
    }
    .hljs-comment {
      color: #6a737d;
    }
    .hljs-variable {
      color: #e36209;
    }
  }
}

// 动画效果
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-5px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.el-message {
  animation: fadeIn 0.3s ease;
}

// 添加过渡动画
.copy-btn {
  transition: all 0.3s ease;

  &.copied {
    background-color: #28a745 !important;
    color: white !important;
  }
}

// 添加动画效果
@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.regenerating .icon {
  animation: spin 1s linear infinite;
}
</style>